var Path = require('path');
var Webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
// var ImageminPlugin = require('imagemin-webpack-plugin').default;
// var ImageminMozjpeg = require('imagemin-mozjpeg');
// var QiniuPlugin = require('qiniu-webpack-plugin');
var WebpackCleanupPlugin = require('webpack-cleanup-plugin')
    // var OpenBrowserPlugin = require('open-browser-webpack-plugin');
var config = require('./config.js');

var resolve = {
    extensions: ['', '.js', '.css', '.scss', '.png', '.jpg', '.ts', '.vue', '.html'],
    alias: {
        "jquery": Path.join(__dirname, 'bower_components', 'jquery/dist/jquery.js')
    }
}
var loaders = [
    { test: /\.ts$/, loader: 'ts-loader' },
    { test: /\.vue$/, loader: 'vue-loader' },
    { test: /\.html$/, loader: "html-loader" },
    {
        test: /\.(png|gif|jpe?g)$/,
        loader: 'url-loader',
        query: {
            limit: 1,
            name: 'images/[hash:8].[ext]'
        }
    },
    // {
    //     test: /\.(eot|woff|woff2|ttf|svg)$/,
    //     loader: 'url-loader',
    //     query: {
    //         limit: 1,
    //         name: '/font/[name]-[hash:8].[ext]'
    //     }
    // },
    // the url-loader uses DataUrls.
    // the file-loader emits files.
    {
        test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        // Limiting the size of the woff fonts breaks font-awesome ONLY for the extract text plugin
        // loader: "url?limit=10000"
        loader: "url"
    },
    {
        test: /\.(ttf|eot|svg)(\?[\s\S]+)?$/,
        loader: 'file'
    },
    {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader!sass-loader!postcss-loader", {
            publicPath: "../"
        })
    },
    {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader!sass-loader", {
            publicPath: "../"
        })
    }
];
var plugins = [
    // new Webpack.DllReferencePlugin({
    //     context: __dirname,
    //     manifest: require("./vendor/vendor-manifest.json")
    // }),
    /*
     * Search for equal or similar files and deduplicate them in the output
     * （删除重复依赖的文件）
     */
    new Webpack.optimize.DedupePlugin(),
    /*
     * Using this config the vendor chunk should not be changing its hash unless you change its code or dependencies
     * （避免在文件不改变的情况下hash值不变化）
     */
    new Webpack.optimize.OccurenceOrderPlugin(),
    new Webpack.DefinePlugin({
        __MAIN__: JSON.stringify(Path.resolve(__dirname, 'src', config.path)),
        __LIBS__: JSON.stringify(Path.resolve(__dirname, 'libs')),
        __VIEWS__: JSON.stringify(Path.resolve(__dirname, 'src', config.path, 'views')),
        __SERVICES__: JSON.stringify(Path.resolve(__dirname, 'services')),
        __COMPONENTS__: JSON.stringify(Path.resolve(__dirname, 'src', config.path, 'components'))
    }),
    // new ImageminPlugin({
    //     pngquant: {
    //         quality: 10
    //     },
    //     plugins: [
    //         ImageminMozjpeg({
    //             progressive: true
    //         })
    //     ]
    // }),
    /***********************************************
    new Webpack.optimize.CommonsChunkPlugin(
        devServer ?
            { name: "common", filename: "js/common.js" } :
            { names: ["common", "webpackAssets"] }
    ),
    new Webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery",
        "window.jQuery": "jquery",
        "avalon": "avalon2",
        "window.avalon": "avalon2"
    }),
    ***********************************************/
];

for (let key in config.html) {
    let chunks = []
    config.html[key].forEach(function(e) {
        chunks.push(e)
    }, this);
    plugins.push(new HtmlWebpackPlugin({
        template: "./src/" + config.path + '/' + key + '.html',
        inject: false,
        minify: {
            removeComments: true,
            collapseWhitespace: true,
            removeAttributeQuotes: true
        },
        chunksSortMode: 'dependency',
        chunks: chunks
    }))

}
var output = {}
switch (process.env.npm_lifecycle_event) {
    case "release":
        // var output = {
        //     path: './build/' + config.path,
        //     filename: 'js/[name]-[chunkhash:5].js',
        //     chunkFilename: 'js/[name]-[chunkhash:5].js'
        // }
        var output = {
            path: './build/' + config.path,
            filename: 'js/[name].js',
            chunkFilename: 'js/[name].js'
        }
        plugins.push(new ExtractTextPlugin("css/style.css", { allChunks: true }))
        plugins.push(new WebpackCleanupPlugin())
        // plugins.push(new Webpack.optimize.UglifyJsPlugin({
        //     compress: {
        //         screw_ie8: false,
        //         warnings: false
        //     },
        //     output: {
        //         screw_ie8: false,
        //         comments: false
        //     },
        //     mangle: false
        // }));
        var devServer = {
            contentBase: output.path,
            port: 8081
        }
        break;
        // plugins.push(new QiniuPlugin({
        //     ACCESS_KEY: 'iAeJF0UXDw2YplNbTHgNP9fSdjcgGzXQpXHTVWDo',
        //     SECRET_KEY: 'JC7MccZR5aiS70wUPxzx5O53XiUPiuwJgcDViGHv',
        //     bucket: 'shindousaigo',
        //     path: ''
        // }))
        // output.publicPath = "http://on56b65dl.bkt.clouddn.com/"
    default:
        var output = {
            path: './build/' + config.path,
            filename: 'js/[name].js',
            chunkFilename: 'js/[name].js'
        }
        plugins.push(new ExtractTextPlugin("css/style.css", { allChunks: true }))
        var devServer = {
            contentBase: "./src/" + config.path,
            port: 8080
        }
        break;
}

module.exports = {
    entry: config.entry,
    output: output,
    resolve: resolve,
    resolveLoader: { root: Path.join(__dirname, "node_modules") },
    plugins: plugins,
    module: {
        loaders: loaders
    },
    postcss: function() {
        return [
            require('postcss-simple-vars'),
            require('postcss-ant'),
            require('autoprefixer'),
        ];
    },
    devServer: devServer
};